package com.example.ymm.modules1.service.xft;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.cmb.xft.open.api.BaseReqInf;
import com.cmb.xft.open.api.HttpResponseData;
import com.cmb.xft.open.api.XftOpenApiReqClient;
import com.example.ymm.exception.YmException;
import com.example.ymm.model.TableList;
import com.example.ymm.model.YmPageDto;
import com.example.ymm.modules1.entity.hl.yw.YwApprove;
import com.example.ymm.modules1.entity.hl.yw.YwMoneyAffirmLog;
import com.example.ymm.modules1.query.hl.YwApproveQueryCriteria;
import com.example.ymm.modules1.service.dto.heng.ImportJsonDataDto;
import com.example.ymm.modules1.service.dto.heng.ImportXftDataDto;
import com.example.ymm.modules1.service.dto.heng.XftApproveCreateDto;
import com.example.ymm.modules1.service.hl.YwApproveService;
import com.example.ymm.modules1.service.hl.YwUserService;
import com.example.ymm.modules1.service.ms.DEmployeeService;
import com.example.ymm.util.*;
import com.google.gson.Gson;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.core.io.ClassPathResource;
import org.springframework.stereotype.Service;
import org.springframework.util.FileCopyUtils;
import org.springframework.util.StreamUtils;

import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.nio.charset.StandardCharsets;
import java.util.*;
import java.util.concurrent.TimeUnit;

@Slf4j
@Service
public class XftService {

    @Value("${xft.domain}")
    String domain;
    @Value("${xft.companyId}")
    String companyId;
    @Value("${xft.appId}")
    String appId;
    @Value("${xft.authoritySecret}")
    String authoritySecret;

    @Value("${xft.procKey}")
    String procKey;


    @Autowired
    RedisUtil redisUtil;

    @Value("${xft.formId}")
    String formId;

    String lqfUserNo="V00JC";//刘庆峰 的企业用户编号

    @Autowired
    YwUserService ywUserService;

    @Autowired
    DEmployeeService dEmployeeService;

    @Autowired
    YwApproveService ywApproveService;


    public JSONObject buildUserNo(String userNo){
        JSONObject parameters = new JSONObject();
        List<JSONObject> queryFilterList=new ArrayList<JSONObject>();
        JSONObject queryFilter=new JSONObject();
        queryFilter.put("fieldKey","stfNumber");
        queryFilter.put("fieldQueryMethod","FUZZY");
        queryFilter.put("fieldValue",userNo);
        queryFilterList.add(queryFilter);
        parameters.put("queryFilterList", queryFilterList);

        JSONObject queryResultType=new JSONObject();
        queryResultType.put("queryType","GROUP");
//        List<String> queryClassKeyList=new ArrayList<>();
//        queryClassKeyList.add("stfSeq");
//        queryClassKeyList.add("stfNumber");
//        queryClassKeyList.add("stfName");
        String s="S01BASIC,S02ONJOB,S03PERSN,S04SAISR,S05CONTACT,S06EMCNT,S07EDUCA,S08WRKEPR,S02QUITMSG,S09TXOTH,S09TXSTA,SO9FMLMEM,S09PFSCER,S09RWDPNS,SO9TTITLE,S09TUTRAN,S09TUVPFE,S10PSNPFL";
        String[] split = s.split(",");
        queryResultType.put("queryClassKeyList",split);
        parameters.put("queryResultType",queryResultType);
        parameters.put("currentPage", 1);
        parameters.put("pageSize", 1);
        return parameters;
    }

    /**
     * 根据工号查询用户信息
     * @param userNo
     *
     *
     */
    public JSONObject getStaffInfoByUserNo(String userNo) {
        String url = domain+ "/hrm/hrm2/xft-employeeprofile/employee/external/api/query/staffInfo";
        /* 加密和解密密文的key */
        String key = authoritySecret.substring(0, 32);
        /* 2.公共信息构建 */
        BaseReqInf baseReqInf = new BaseReqInf(appId, authoritySecret);
//        baseReqInf.setUsrNbr("A0001");
//        baseReqInf.setUsrUid("AUTO0001");
        /* 3. 请求报文、queryParam构建：字符串形式(推荐使用方式)*/
        JSONObject parameters = buildUserNo(userNo);

        String requestBody =  parameters.toJSONString();
//        System.out.println("--参数");
//        System.out.println(requestBody);
        String secretMsg = null;
        try {
            secretMsg = Sm4Util.encryptEcb(key, requestBody);
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
        Map<String, String> newRequestBodyMap = new HashMap<>();
       // secretMsg这个名称固定
        newRequestBodyMap.put("secretMsg", secretMsg);
        Gson gson = new Gson();
        requestBody = gson.toJson(newRequestBodyMap);
        /* url里面除了公共参数（CSCAPPUID，CSCPRJCOD，CSCUSRUID，CSCREQTIM，CSCUSRNBR）的其他参数 */
        String queryString = "{}";
        Gson gs = new Gson();
        Map<String, Object> queryParam = gs.fromJson(queryString,Map.class);
        /* 4.调用接口 */
        HttpResponseData postReqResult = null;
        try {
            postReqResult = XftOpenApiReqClient.doCommonPostReq(baseReqInf, url, queryParam,requestBody);
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
        String responseBody = postReqResult.getBody();
        JSONObject json=null;
        JSONObject dataJson=null;
        try {
            responseBody = Sm4Util.decryptEcb(key, responseBody);
            //System.out.println("----responseBody:"+responseBody);
            json=JSONObject.parseObject(responseBody);
            if("SUC0000".equals(json.getString("returnCode"))){
                JSONArray list= json.getJSONObject("body").getJSONArray("records");
                dataJson=list.getJSONObject(0);
            }else{
                throw new YmException(json.getString("errorMsg"));
            }
        } catch (Exception e) {
            throw  new YmException(responseBody);
        }

        return dataJson;
    }


    /**
     * 根据姓名查询企业成员信息
     * @param userName
     * @return
     */
    public JSONObject getMemberInfoByUserName(String userName) {
        /* 加密和解密密文的key */
        String key = authoritySecret.substring(0, 32);
        /* 请求路径（以测试环境为例）*/
        String url = domain+"/xft-member/openapi/xft-member/member/page/by-condition";
        /* 2.公共信息构建 */
        BaseReqInf baseReqInf = new BaseReqInf(companyId,appId, authoritySecret);
//        baseReqInf.setUsrNbr("A0001");
//        baseReqInf.setUsrUid("AUTO0001");
        JSONObject parameters = new JSONObject();
        parameters.put("currentPage",1);
        parameters.put("pageSize",10);
        parameters.put("name",userName);
        /* 3. 请求报文、queryParam构建：字符串形式(推荐使用方式)*/
        String requestBody =  parameters.toJSONString();
        String secretMsg = null;
        try {
            secretMsg = Sm4Util.encryptEcb(key, requestBody);
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
        Map<String, String> newRequestBodyMap = new HashMap<>();
// secretMsg这个名称固定
        newRequestBodyMap.put("secretMsg", secretMsg);
        Gson gson = new Gson();
        requestBody = gson.toJson(newRequestBodyMap);
        /* url里面除了公共参数（CSCAPPUID，CSCPRJCOD，CSCUSRUID，CSCREQTIM，CSCUSRNBR）的其他参数 */
        String queryString = "{}";
        Gson gs = new Gson();
        Map<String, Object> queryParam = gs.fromJson(queryString,Map.class);
        /* 4.调用接口 */
        HttpResponseData postReqResult = null;
        try {
            postReqResult = XftOpenApiReqClient.doCommonPostReq(baseReqInf, url, queryParam,requestBody);
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
        String responseBody = postReqResult.getBody();
        JSONObject json=null;
        JSONObject dataJson=null;
        try {
            responseBody = Sm4Util.decryptEcb(key, responseBody);
            json=JSONObject.parseObject(responseBody);
            if("SUC0000".equals(json.getString("returnCode"))){
                JSONArray list= json.getJSONObject("body").getJSONArray("records");
                if(list.size()>0){
                    dataJson=list.getJSONObject(0);
                }else{
                    throw new YmException("薪福通无此账号："+userName);
                }
            }else{
                throw new YmException(json.getString("errorMsg"));
            }
        } catch (Exception e) {
            throw  new YmException( e.getMessage());
        }
        return dataJson;
    }

    /**
     * 流程试算
     * @return
     */
    public JSONObject approveTrialFn(XftApproveCreateDto dto){
        JSONObject result = null;
        JSONObject busDataValue = createBusData(dto);
//        System.out.println("---busDataValue");
//        System.out.println(busDataValue);
        /**
         * 构建业务数据 busData 参数
         */
        JSONObject busDatajson = new JSONObject();
        busDatajson.put("value",busDataValue);
        busDatajson.put("mappings",new ArrayList<>());
        result =approveTrial(dto,busDatajson);
        return result;
    }

    /**
     * 薪福通 流程试算
     * p userNo 用户编号
     * @return
     */
    public JSONObject approveTrial(XftApproveCreateDto dto, JSONObject busDatajson){
        System.out.println("--发出流程试算请求:");
        /* 1.基本信息内容 */
        /* 开放平台 appId */
        /* 开放平台 authoritySecret */
        /* 加密和解密密文的key */
        String key = authoritySecret.substring(0, 32);
        /* 请求路径（以测试环境为例）*/
        String url = "https://api.cmbchina.com/xft-oa/openapi/xft-oa/open/operate/proc/inst/trial";
        /* 2.公共信息构建 */
        BaseReqInf baseReqInf = new BaseReqInf(appId, authoritySecret);
//        baseReqInf.setUsrNbr("A0001");
//        baseReqInf.setUsrUid("AUTO0001");
        /* 3. 请求报文、queryParam构建：字符串形式(推荐使用方式)*/
        JSONObject parameters = new JSONObject();
        parameters.put("starterId",dto.getMemberId());
        parameters.put("trialType","startTrial");
        parameters.put("procKey",procKey);
//        String busData="{\\\"value\\\":{\\\"df8be730f7d411efb858f5f951324701\\\":\\\"test_123\\\",\"mappings\":[]}}";
        parameters.put("busData",busDatajson.toJSONString());
//        System.out.println("--流程试算:");
//        System.out.println(parameters.toJSONString());
        String requestBody =  parameters.toJSONString();

        //System.out.println("---requestBody:"+requestBody);
        String secretMsg = null;
        try {
            secretMsg = Sm4Util.encryptEcb(key, requestBody);
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
        Map<String, String> newRequestBodyMap = new HashMap<>();
        // secretMsg这个名称固定
        newRequestBodyMap.put("secretMsg", secretMsg);
        Gson gson = new Gson();
        requestBody = gson.toJson(newRequestBodyMap);
        /* url里面除了公共参数（CSCAPPUID，CSCPRJCOD，CSCUSRUID，CSCREQTIM，CSCUSRNBR）的其他参数 */
        String queryString = "{}";
        Gson gs = new Gson();
        Map<String, Object> queryParam = gs.fromJson(queryString,Map.class);
        /* 4.调用接口 */
        HttpResponseData postReqResult = null;
        try {
            postReqResult = XftOpenApiReqClient.doCommonPostReq(baseReqInf, url, queryParam,requestBody);
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
        String responseBody = postReqResult.getBody();
        JSONObject json=null;
        JSONObject dataJson=null;
        try {
            responseBody = Sm4Util.decryptEcb(key, responseBody);
            json=JSONObject.parseObject(responseBody);
        //    System.out.println("--json:"+json);
            if("SUC0000".equals(json.getString("returnCode"))){
                dataJson=json.getJSONObject("body");
                return dataJson;
               // System.out.println("--结果:"+dataJson);
            }else{
               throw  new YmException(json.getString("errorMsg"));
            }

        } catch (Exception e) {
            throw  new YmException( responseBody);
        }
    }


    public JSONObject approveCreate(XftApproveCreateDto dto){
        /* 加密和解密密文的key */
        String key = authoritySecret.substring(0, 32);
        /* 请求路径（以测试环境为例）*/
        String url = "https://api.cmbchina.com/xft-oa/openapi/xft-oa/open/operate/proc/inst/start";
        /* 2.公共信息构建 */
        BaseReqInf baseReqInf = new BaseReqInf(appId, authoritySecret);
//        baseReqInf.setUsrNbr("A0001");
//        baseReqInf.setUsrUid("AUTO0001");
        /* 3. 请求报文、queryParam构建：字符串形式(推荐使用方式)*/

        JSONObject parameters = new JSONObject();
        parameters.put("starterId",dto.getMemberId());
        parameters.put("trialId",dto.getTrialData().getString("trialId"));

//        System.out.println("----parameters");
//        System.out.println(parameters.toJSONString());

        String requestBody =  parameters.toJSONString();
        String secretMsg = null;
        try {
            secretMsg = Sm4Util.encryptEcb(key, requestBody);
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
        Map<String, String> newRequestBodyMap = new HashMap<>();
// secretMsg这个名称固定
        newRequestBodyMap.put("secretMsg", secretMsg);
        Gson gson = new Gson();
        requestBody = gson.toJson(newRequestBodyMap);
        /* url里面除了公共参数（CSCAPPUID，CSCPRJCOD，CSCUSRUID，CSCREQTIM，CSCUSRNBR）的其他参数 */
        String queryString = "{}";
        Gson gs = new Gson();
        Map<String, Object> queryParam = gs.fromJson(queryString,Map.class);
        /* 4.调用接口 */
        HttpResponseData postReqResult = null;
//        System.out.println("---requestBody");
//        System.out.println(requestBody);
        try {
            postReqResult = XftOpenApiReqClient.doCommonPostReq(baseReqInf, url, queryParam,requestBody);
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
        String responseBody = postReqResult.getBody();

        JSONObject json=null;
        JSONObject dataJson=null;
        try {
            responseBody = Sm4Util.decryptEcb(key, responseBody);

          //  System.out.println(responseBody);
            json=JSONObject.parseObject(responseBody);
        //    System.out.println("--json:"+json);
            if("SUC0000".equals(json.getString("returnCode"))){
                dataJson=json.getJSONObject("body");
                return dataJson;
            }else{
                throw  new YmException(json.getString("errorMsg"));
            }
        } catch (Exception e) {
            throw  new YmException( responseBody);
        }
    }

//    public  JSONObject approveSubmit(String userNo,String busKey){
//        return approveDeal(userNo,busKey,"submit");
//    }

    public  JSONObject approveDeal(String userNo,String busKey,String operateType){
        /* 加密和解密密文的key */
        String key = authoritySecret.substring(0, 32);
        /* 请求路径（以测试环境为例）*/
        String url = "https://api.cmbchina.com/xft-oa/openapi/xft-oa/open/operate/proc/inst/deal";
        /* 2.公共信息构建 */
        BaseReqInf baseReqInf = new BaseReqInf(appId, authoritySecret);
//        baseReqInf.setUsrNbr("A0001");
//        baseReqInf.setUsrUid("AUTO0001");
        /* 3. 请求报文、queryParam构建：字符串形式(推荐使用方式)*/
        JSONObject parameters = new JSONObject();
        parameters.put("approverId",userNo);
        parameters.put("operateType",operateType);
        parameters.put("busKey",busKey);
        String requestBody =  parameters.toJSONString();
        String secretMsg = null;
        try {
            secretMsg = Sm4Util.encryptEcb(key, requestBody);
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
        Map<String, String> newRequestBodyMap = new HashMap<>();
// secretMsg这个名称固定
        newRequestBodyMap.put("secretMsg", secretMsg);
        Gson gson = new Gson();
        requestBody = gson.toJson(newRequestBodyMap);
        /* url里面除了公共参数（CSCAPPUID，CSCPRJCOD，CSCUSRUID，CSCREQTIM，CSCUSRNBR）的其他参数 */

        String queryString = "{}";
        Gson gs = new Gson();
        Map<String, Object> queryParam = gs.fromJson(queryString,Map.class);
        /* 4.调用接口 */
        HttpResponseData postReqResult = null;
        try {
            postReqResult = XftOpenApiReqClient.doCommonPostReq(baseReqInf, url, queryParam,requestBody);
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
        String responseBody = postReqResult.getBody();
        JSONObject json=null;
        JSONObject dataJson=null;
        try {
            responseBody = Sm4Util.decryptEcb(key, responseBody);
//            System.out.println(responseBody);
            json=JSONObject.parseObject(responseBody);
//            System.out.println("--json:"+json);
            if("SUC0000".equals(json.getString("returnCode"))){
                dataJson=json.getJSONObject("body");
                return dataJson;
            }else{
                throw  new YmException(json.getString("errorMsg"));
            }
        } catch (Exception e) {
            throw  new YmException(responseBody);

        }
//        return null;
    }


    public  JSONObject approveCancel(String userNo,String busKey){

        return approveDeal(userNo,busKey,"cancel");
    }


    /**
     * 获取表单配置信息
     * @return
     */
    public JSONArray getFormInfo(){
        /* 1.基本信息内容 */
        /* 开放平台 appId */
        /* 开放平台 authoritySecret */
        /* 加密和解密密文的key */
        String key = authoritySecret.substring(0, 32);
        /* 请求路径（以测试环境为例）*/
        String url = domain+"/xft-oa/openapi/xft-oaquery/form-config/query";
        /* 2.公共信息构建 */
        BaseReqInf baseReqInf = new BaseReqInf(appId, authoritySecret);
        baseReqInf.setUsrNbr("A0001");
        baseReqInf.setUsrUid("AUTO0001");
        /* 3. 请求报文、queryParam构建：字符串形式(推荐使用方式)*/
        JSONObject parameters = new JSONObject();
        parameters.put("formId","282414045544054785:11");
        String requestBody =  parameters.toJSONString();
        String secretMsg = null;
        try {
            secretMsg = Sm4Util.encryptEcb(key, requestBody);
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
        Map<String, String> newRequestBodyMap = new HashMap<>();
       // secretMsg这个名称固定
        newRequestBodyMap.put("secretMsg", secretMsg);
        Gson gson = new Gson();
        requestBody = gson.toJson(newRequestBodyMap);
        /* url里面除了公共参数（CSCAPPUID，CSCPRJCOD，CSCUSRUID，CSCREQTIM，CSCUSRNBR）的其他参数 */
        String queryString = "{}";
        Gson gs = new Gson();
        Map<String, Object> queryParam = gs.fromJson(queryString,Map.class);
        /* 4.调用接口 */
        HttpResponseData postReqResult = null;

        try {
            postReqResult = XftOpenApiReqClient.doCommonPostReq(baseReqInf, url, queryParam,requestBody);

        } catch (Exception e) {
            throw new RuntimeException(e);
        }
        String responseBody = postReqResult.getBody();
        JSONObject json=null;
        JSONObject dataJson=null;
        JSONArray list = null;
        try {
            responseBody = Sm4Util.decryptEcb(key, responseBody);
            json=JSONObject.parseObject(responseBody);

            if("SUC0000".equals(json.getString("returnCode"))){
                dataJson=json.getJSONObject("body");
                String formConfig = dataJson.getString("formConfig");
                list=JSONObject.parseArray(formConfig);
//                System.out.println("--结果:"+formConfig);
//                System.out.println(dataJson);
            }else{
                throw  new YmException(json.getString("errorMsg"));
            }
        } catch (Exception e) {
            System.out.println("解密失败：" + responseBody);
        }
        return list;
    }



    public  JSONObject createBusData(XftApproveCreateDto dto){
        JSONObject parameters = new JSONObject();
        parameters.put("36467ef004a511f0b96fbfec4c6a15c2",dto.getApproveNo());//审批编号
        //抽成明细字段
        JSONObject formInfo_json = new JSONObject();//字段收集到这个json当中

        String addId="f67744f004a211f0b96fbfec4c6a15c2";//抽成明细

        ClassPathResource formInfoJson = new ClassPathResource("formInfo.json");// 表单id: 282414045544054785:2
        InputStream formInfoInputStream = null;
        String formInfo_json_str=null;
        try {
            formInfoInputStream = formInfoJson.getInputStream();
            formInfo_json_str =  StreamUtils.copyToString(formInfoInputStream, StandardCharsets.UTF_8);
            formInfoInputStream.close();
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
        JSONArray formInfos =JSONObject.parseArray(formInfo_json_str);
        JSONArray f_lists= formInfos.getJSONObject(1).getJSONObject("options").getJSONArray("controls").getJSONObject(0).getJSONObject("options").getJSONArray("controls");
        for(int i=0;i<f_lists.size();i++){
            JSONArray f = f_lists.getJSONObject(i).getJSONObject("options").getJSONArray("controls");
            for(int j=0;j<f.size();j++){
                JSONObject jsonObject = f.getJSONObject(j).getJSONObject("options");
                formInfo_json.put(jsonObject.getString("placeholder"),jsonObject.getString("field"));
            }
        }
//        System.out.println("---字段json:");
//        System.out.println(formInfo_json);
        //抽成明细-数据
        List<JSONObject> dataList = new ArrayList<>();
        String jsonString = JSONObject.toJSONString(dto);
        JSONArray objects = JSONObject.parseObject(jsonString).getJSONArray("list");

        Map<String,String> priceMap=new HashMap<>();
//        System.out.println("---数据");
//        System.out.println(objects);
        for(int i=0;i<objects.size();i++){
            JSONObject object = objects.getJSONObject(i);
            JSONObject busDataJson = new JSONObject();
            Set<Map.Entry<String, Object>> entries = formInfo_json.entrySet();
            for(Map.Entry<String, Object> entry: entries){
                String field_id = entry.getValue().toString();
                String key = entry.getKey();

                if(object.containsKey(key)){
                    if("payTime".equals(key)){
                        Date date = new Date(object.getLong(key));
                        String s = DateKit.dateFormat(date);
                        busDataJson.put(field_id,s);
                    }else{
                        busDataJson.put(field_id,object.get(key));
                    }

                }else{
                    busDataJson.put(field_id,"");
                }

                if("totalAllPrice".equals(key)||"orderCommissionPrice".equals(key)||"receiverUserPrice".equals(key)||"merchandiserUserPrice".equals(key)
                ||"manageUserPrice".equals(key)||"xiangMuGroupPrice".equals(key)||"jiJingPrice".equals(key)){

                    priceMap.put(field_id,object.getString(key));

                    JSONObject moneyJson = new JSONObject();
                    moneyJson.put("currency",1);
                    if(UtilValidate.isNotEmpty(busDataJson.getString(field_id))){
                        moneyJson.put("number",busDataJson.getBigDecimal(field_id));
                    }
                    busDataJson.put(field_id,moneyJson);
                }
            }

            String rowKey= UuidUtils.getUUID();
            busDataJson.put("rowKey",rowKey);
            dataList.add(busDataJson);

            String o_key=addId+"-"+rowKey;

            for(String key2: busDataJson.keySet()){
                String p_key=o_key+"-"+key2;
                if(priceMap.containsKey(key2)){

                    parameters.put(p_key,JSONObject.parseObject(busDataJson.getString(key2)));
                }else{
                    parameters.put(p_key,busDataJson.get(key2));
                }
            }
        }

        parameters.put(addId,dataList);//新增

//        ClassPathResource busDataJson = new ClassPathResource("busData.json");// 表单id: 282414045544054785:2
//        InputStream busDatainputStream = null;
//        String busData_json_str=null;
//        try {
//            busDatainputStream = busDataJson.getInputStream();
//            busData_json_str = StreamUtils.copyToString(busDatainputStream, StandardCharsets.UTF_8);
//            busDatainputStream.close();
//        } catch (IOException e) {
//            throw new RuntimeException(e);
//        }

        return parameters;
    }


    /**
     * 表单字段解析
     * @param
     * @return
     */
    public static Map<String,String> doFormInfo(JSONArray objects){
        Map<String,String> map=new HashMap<>();
        for(int i=0;i<objects.size();i++){
            JSONObject jsonObject = objects.getJSONObject(i);
            forEachSetValue(jsonObject,map);
        }
        return  map;
    }


    public static void forEachSetValue(JSONObject json,Map<String,String> map){
        if("Container".equals(json.getString("type"))){
            JSONArray jsonArray = json.getJSONObject("options").getJSONArray("controls");
            for(int i=0;i<jsonArray.size();i++){
                JSONObject jsonObject = jsonArray.getJSONObject(i);
                JSONObject jsonObject1 = jsonObject.getJSONObject("options");
                forEachSetValue(jsonObject1,map);
            }
        }else{
            if(json.containsKey("placeholder")&& UtilValidate.isNotEmpty(json.getString("placeholder"))){
                map.put(json.getString("placeholder"),json.getString("field"));

            }
        }
    }




    /**
     * 导入采集数据
     * @param dto
     * @return
     */
    public JSONArray importJsonData(ImportJsonDataDto dto){
        /* 1.基本信息内容 */
        /* 开放平台 appId */
        /* 开放平台 authoritySecret */
        /* 加密和解密密文的key */
        String key = authoritySecret.substring(0, 32);
        /* 请求路径（以测试环境为例）*/
        String url = domain+"/sal/sal/xft-sly/salary/api/import-collection-data";
        /* 2.公共信息构建 */
        BaseReqInf baseReqInf = new BaseReqInf(appId, authoritySecret);
//        baseReqInf.setUsrNbr("A0001");
//        baseReqInf.setUsrUid("AUTO0001");
        /* 3. 请求报文、queryParam构建：字符串形式(推荐使用方式)*/
        JSONObject parameters = buildImportJsonData(dto);

//        redisUtil.setIfAbsent(dto.getApproveNo(),parameters.toJSONString(),10, TimeUnit.MINUTES);
        String requestBody =  parameters.toJSONString();

        System.out.println("---推送采集表:"+requestBody);
//
//        System.out.println(parameters);
        String secretMsg = null;
        try {
            secretMsg = Sm4Util.encryptEcb(key, requestBody);
        } catch (Exception e) {
            log.error(e.getMessage(),e);
            throw new RuntimeException(e);
        }
        Map<String, String> newRequestBodyMap = new HashMap<>();
        // secretMsg这个名称固定
        newRequestBodyMap.put("secretMsg", secretMsg);
        Gson gson = new Gson();
        requestBody = gson.toJson(newRequestBodyMap);
        /* url里面除了公共参数（CSCAPPUID，CSCPRJCOD，CSCUSRUID，CSCREQTIM，CSCUSRNBR）的其他参数 */
        String queryString = "{}";
        Gson gs = new Gson();
        Map<String, Object> queryParam = gs.fromJson(queryString,Map.class);
        /* 4.调用接口 */
        HttpResponseData postReqResult = null;
        try {
            postReqResult = XftOpenApiReqClient.doCommonPostReq(baseReqInf, url, queryParam,requestBody);
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
        String responseBody = postReqResult.getBody();
        JSONObject json=null;
        JSONObject dataJson=null;
        try {
            responseBody = Sm4Util.decryptEcb(key, responseBody);
            json=JSONObject.parseObject(responseBody);
            System.out.println("--推送结果json:"+json);
            if("SUC0000".equals(json.getString("returnCode"))){
//                dataJson=json.getJSONObject("body");
                return json.getJSONArray("body");
                // System.out.println("--结果:"+dataJson);
            }else{
                throw  new YmException(json.getString("errorMsg"));
            }

        } catch (Exception e) {
            System.out.println("解密失败：" + responseBody);
        }
        return null;
    }


    public JSONObject buildImportJsonData(ImportJsonDataDto dto){
        JSONObject parameters = new JSONObject();
        JSONObject importConfigInfo=new JSONObject();

        // String type; 数据推送类型:配送费审批，业务员抽成审批
        String tableName=null;
        String approveMapping_json_str=null;
        String type = dto.getType();
        if("配送费审批".equals(type)){
            tableName="自研配送费薪资表";
            approveMapping_json_str="{\n" +
                    "  \"审批编号\":\"approveNo\",\n" +
                    "  \"名称\":\"userName\",\n" +
                    "  \"薪资\":\"userPrice\",\n" +
                    "  \"身份\":\"userType\",\n" +
//                    "  \"部门\t\n\":\"deptName\",\n" +
                    "  \"备注\":\"deptName\",\n" +
                    "  \"审批类型\":\"approveType\"\n" +
                    "}";
        }else if("业务员抽成审批".equals(type)){
            tableName="自研业务抽成薪资表";
            approveMapping_json_str="{\n" +
                    "  \"审批编号\":\"approveNo\",\n" +
                    "  \"名称\":\"userName\",\n" +
                    "  \"薪资\":\"userPrice\",\n" +
                    "  \"身份\":\"userType\",\n" +
//                    "  \"部门\":\"deptName\",\n" +
                    "  \"备注\":\"deptName\"\n" +
                    "}";
        }
        importConfigInfo.put("dataCollectionName",tableName);
        importConfigInfo.put("importType","ADD");

        YwApprove approve = dto.getApprove();
//        Date date = new Date(approve.getCreateTime().getTime());
//        String dateStr=DateKit.dateFormat(date,"yyyyMM");
        String addTime ="";
        if(UtilValidate.isEmpty(dto.getMonth())){
            Date lastMonthBegin = DateKit.getLastMonthBegin();//自动获取上个月的日期
            addTime = DateKit.dateFormat(lastMonthBegin, "yyyyMM");
        }else{
            addTime =dto.getMonth();
        }

        importConfigInfo.put("salaryPeriod",addTime);//薪资所属期
        parameters.put("importConfigInfo",importConfigInfo);

        List<ImportXftDataDto> list = dto.getList();


//        ClassPathResource resource = new ClassPathResource("importApproveMapping.json");// 表单id: 282414045544054785:2
        InputStream formInfoInputStream = null;

//        try {
//            formInfoInputStream = resource.getInputStream();
//            approveMapping_json_str = StreamUtils.copyToString(formInfoInputStream, StandardCharsets.UTF_8);
//            formInfoInputStream.close();
//        } catch (IOException e) {
//            throw new RuntimeException(e);
//        }

        JSONObject approveMapping =JSONObject.parseObject(approveMapping_json_str);
        approveMapping.put("部门","");

        List<JSONObject> collectionDataList=new ArrayList<>();
        for(ImportXftDataDto dataDto: list){
            JSONObject jsonObject=new JSONObject();

            JSONObject json1 = buildImportItem(dataDto, approveMapping);
            json1.put("薪资所属期",addTime);
            jsonObject.put("collectionData", json1.toString());
            collectionDataList.add(jsonObject);
        }
        parameters.put("collectionDataList",collectionDataList);
        return parameters;
    }


    public JSONObject buildImportItem(ImportXftDataDto dataDto,JSONObject approveMapping){
        JSONObject parameters = new JSONObject();
        JSONObject dataJson=JSONObject.parseObject(JSONObject.toJSONString(dataDto));
        for(String a_key:approveMapping.keySet()){
            Object o = dataJson.get(approveMapping.getString(a_key));
            if(UtilValidate.isNotEmpty(o)){
                parameters.put(a_key,o);
            }else{
                parameters.put(a_key,"");
            }
//            if("收款日期".equals(a_key)){
//                Date date=new Date((Long) o);
//                String dateStr=DateKit.dateFormat(date);
//                parameters.put(a_key,dateStr);
//            }
        }
        return parameters;
    }


    /**
     * 获取审批历史
     * @return
     */
    public JSONArray approvalHistory(String busKey){
        /* 加密和解密密文的key */
        String key = authoritySecret.substring(0, 32);
        /* 请求路径（以测试环境为例）*/
        String url = domain+"/xft-oa/openapi/xft-oaquery/proc/inst/query-approval-histories";
        /* 2.公共信息构建 */
        BaseReqInf baseReqInf = new BaseReqInf(companyId,appId, authoritySecret);
//        baseReqInf.setUsrNbr("A0001");
//        baseReqInf.setUsrUid("AUTO0001");
        /* 3. 请求报文、queryParam构建：字符串形式(推荐使用方式)*/
        JSONObject params = new JSONObject();
        params.put("busKey",busKey);
        String requestBody =  params.toJSONString();
        String secretMsg = null;
        try {
            secretMsg = Sm4Util.encryptEcb(key, requestBody);
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
        Map<String, String> newRequestBodyMap = new HashMap<>();
// secretMsg这个名称固定
        newRequestBodyMap.put("secretMsg", secretMsg);
        Gson gson = new Gson();
        requestBody = gson.toJson(newRequestBodyMap);
        /* url里面除了公共参数（CSCAPPUID，CSCPRJCOD，CSCUSRUID，CSCREQTIM，CSCUSRNBR）的其他参数 */
        String queryString = "{}";
        Gson gs = new Gson();
        Map<String, Object> queryParam = gs.fromJson(queryString,Map.class);
        /* 4.调用接口 */
        HttpResponseData postReqResult = null;
        try {
            postReqResult = XftOpenApiReqClient.doCommonPostReq(baseReqInf, url, queryParam,requestBody);
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
        String responseBody = postReqResult.getBody();
        JSONObject json=null;
        JSONArray jsonArray=null;
        try {
            responseBody = Sm4Util.decryptEcb(key, responseBody);
            System.out.println(responseBody);
            json=JSONObject.parseObject(responseBody);
            if("SUC0000".equals(json.getString("returnCode"))){
                 jsonArray= json.getJSONArray("body");

            }else{
                throw new YmException(json.getString("errorMsg"));
            }
        } catch (Exception e) {
            throw new YmException("解密失败：" + responseBody);
        }
        return jsonArray;
    }


    //查询业务数据
    public TableList<YwApprove> approvalDataList(YwApproveQueryCriteria criteria, YmPageDto pageDto){
        /* 加密和解密密文的key */
        String key = authoritySecret.substring(0, 32);
        /* 请求路径（以测试环境为例）*/
        String url = domain+"/xft-oa/openapi/xft-oaquery/form-data/business/query-page-list";
        /* 2.公共信息构建 */
        BaseReqInf baseReqInf = new BaseReqInf(appId, authoritySecret);
//        baseReqInf.setUsrNbr("A0001");
//        baseReqInf.setUsrUid("AUTO0001");
        /* 3. 请求报文、queryParam构建：字符串形式(推荐使用方式)*/
        JSONObject params = new JSONObject();
        params.put("current",pageDto.getPage());
        params.put("size",pageDto.getPageSize());
        params.put("keywords",criteria.getKeyword());
        params.put("starterId",criteria.getMemberId());
        List<String> formKeyList=new ArrayList<>();
        formKeyList.add("282414045544054785");
        params.put("formKeyList",formKeyList);

        String requestBody = params.toJSONString();
        String secretMsg = null;
        try {
            secretMsg = Sm4Util.encryptEcb(key, requestBody);
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
        Map<String, String> newRequestBodyMap = new HashMap<>();
// secretMsg这个名称固定
        newRequestBodyMap.put("secretMsg", secretMsg);
        Gson gson = new Gson();
        requestBody = gson.toJson(newRequestBodyMap);
        /* url里面除了公共参数（CSCAPPUID，CSCPRJCOD，CSCUSRUID，CSCREQTIM，CSCUSRNBR）的其他参数 */
        String queryString = "{}";
        Gson gs = new Gson();
        Map<String, Object> queryParam = gs.fromJson(queryString,Map.class);
        /* 4.调用接口 */
        HttpResponseData postReqResult = null;
        try {
            postReqResult = XftOpenApiReqClient.doCommonPostReq(baseReqInf, url, queryParam,requestBody);
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
        String responseBody = postReqResult.getBody();
        TableList<YwApprove> tableList=new TableList<>();
        JSONObject json=null;
        JSONArray jsonArray=null;
        List<String> busKeys = new ArrayList<>();
        try {
            responseBody = Sm4Util.decryptEcb(key, responseBody);
            System.out.println(responseBody);
            json=JSONObject.parseObject(responseBody);
            if("SUC0000".equals(json.getString("returnCode"))){
                JSONObject body = json.getJSONObject("body");
                jsonArray= body.getJSONArray("records");
                List<YwApprove> ywApproves=null;
                Map<String,JSONObject> map=new HashMap<>();
                if(UtilValidate.isNotEmpty(jsonArray)){
                    for(int i=0;i<jsonArray.size();i++){
                        JSONObject jsonObject=jsonArray.getJSONObject(i);
                        String busKey = jsonObject.getString("busKey");
                        busKeys.add(busKey);
                        map.put(busKey,jsonObject);
                    }
                    if(UtilValidate.isNotEmpty(busKeys)){
                        YwApproveQueryCriteria approveQueryCriteria = new YwApproveQueryCriteria();
                        approveQueryCriteria.setBusKeyIn(busKeys);
                        ywApproves = ywApproveService.queryAll(approveQueryCriteria);
                        if(UtilValidate.isNotEmpty(ywApproves)){
                            for(YwApprove ywApprove : ywApproves){
                                JSONObject jsonObject = map.get(ywApprove.getBusKey());
                                if(UtilValidate.isNotEmpty(jsonObject)){
                                    ywApprove.setState(jsonObject.getString("status"));
                                }
                            }
                        }
                    }
                    if(UtilValidate.isNotEmpty(ywApproves)){
                        tableList.setList(ywApproves);
                        tableList.setTotalPage(body.getLong("pages"));
                        tableList.setTotalResult(body.getLong("total"));
                    }


                }

            }else{
                throw new YmException(json.getString("errorMsg"));
            }
        } catch (Exception e) {
            throw new YmException(e.getMessage());
        }
        return tableList;
    }



    public static void main(String[] args) {


    }

}
